package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.config.AuthProperties;
import com.changgou.oauth.domain.AuthToken;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author: HuangFu
 * @Date: 2020/2/10 19:37
 * @Description:
 */
@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;
    @Autowired
    private AuthProperties authProperties;

    @PostMapping("/login")
    @ResponseBody
    public Result<AuthToken> login(String username, String password, HttpServletResponse response){
        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不存在");
        }
        if (StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名不存在");
        }
        //申请令牌
        AuthToken authToken = authService.login(username, password);

        //存储Cookie
        CookieUtil.addCookie(response,authProperties.getCookieDomain()
                ,"/","uid",authToken.getJti(),authProperties.getCookieMaxAge(),false);

        return new Result(true, StatusCode.OK,"登录成功",authToken.getJti());
    }

    @GetMapping("/toLogin")
    public String toLogin(@RequestParam(value = "FROM",required = false,defaultValue = "") String from, Model model){
        model.addAttribute("from",from);
        return "login";
    }

}
